package com.yimi.yinhepda.views.main.my_module;

import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;

import com.yimi.yinhepda.R;
import com.yimi.yinhepda.utils.Common;
import com.pda.uce.commom.util.MyDialog;
import com.yimi.yinhepda.base.BaseInitActivity;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * @author: lj
 * Date: 2019/9/20 16:45
 * Description:个性设置
 */
public class SpecificActivity extends BaseInitActivity {

    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    /**
     * 卸车串货
     */
    @Bind(R.id.sw_unLoad_chuanhuo)
    Switch swUnloadChuanhuo;
    /**
     * 装车错分
     */
    @Bind(R.id.sw_load_cuofen)
    Switch swLoadCuofen;
    /**
     * 触屏震动开关
     */
    @Bind(R.id.sw_touch_vibrate)
    Switch swTouchVibrate;
    /**
     * 自适应明暗开关
     */
    @Bind(R.id.sw_auto_light)
    Switch swAutoLight;
    /**
     * 明暗调节 线性布局
     */
    @Bind(R.id.ll_brightness)
    LinearLayout ll_brightness;
    /**
     * 明暗调节
     */
    @Bind(R.id.sb_brightness)
    SeekBar sbBrightness;

    @Bind(R.id.iv_big_brightness)
    ImageView ivBigBrightness;
    @Bind(R.id.iv_small_brightness)
    ImageView ivSmallBrightness;

    private MyDialog mDialog;

    @Override
    public String getPageName() {
        return "个性设置";
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_specific;
    }

    @Override
    public void initView(Bundle savedInstanceState) {

    }

    @Override
    public void initEvent() {
        //明暗调节监听事件
        sbBrightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                setSysScreenBrightness(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    @Override
    public void initData() {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //5.0自定义switch，5.0以下自定义不生效
            swUnloadChuanhuo.setThumbDrawable(getDrawable(R.drawable.switch_custom_thumb_on));
            swUnloadChuanhuo.setTrackDrawable(getDrawable(R.drawable.switch_custom_track_selector));
            swLoadCuofen.setThumbDrawable(getDrawable(R.drawable.switch_custom_thumb_on));
            swLoadCuofen.setTrackDrawable(getDrawable(R.drawable.switch_custom_track_selector));
            swTouchVibrate.setThumbDrawable(getDrawable(R.drawable.switch_custom_thumb_on));
            swTouchVibrate.setTrackDrawable(getDrawable(R.drawable.switch_custom_track_selector));
            swAutoLight.setThumbDrawable(getDrawable(R.drawable.switch_custom_thumb_on));
            swAutoLight.setTrackDrawable(getDrawable(R.drawable.switch_custom_track_selector));
        }
        ivBack.setVisibility(View.VISIBLE);
        sbBrightness.setProgress(getScreenBrightness());
        tvTitle.setText(getPageName());
        //初始化卸车串货提示开关
        swUnloadChuanhuo.setChecked(sharedPreferUtil.getUnLoadChuanHuoSwitch());
        //初始化装车错分开关
        boolean isCheck = sharedPreferUtil.getBooleanValue(Common.LOAD_WRONG_FORCE_SURE);
        swLoadCuofen.setChecked(isCheck);
        //触屏震动开关
        boolean playVirbator = sharedPreferUtil.getBooleanValue(Common.PLAY_VIBRATOR);
        swTouchVibrate.setChecked(playVirbator);
        //默认设置自适应亮度
        ContentResolver contentResolver = getContentResolver();
        if (hasWriteSettingPermission()) {
            if (sharedPreferUtil.getBooleanValue(Common.AUTO_LIGHT)) {
                swAutoLight.setChecked(true);
                ll_brightness.setVisibility(View.GONE);
                Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE,
                        Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
            } else {
                swAutoLight.setChecked(false);
                ll_brightness.setVisibility(View.VISIBLE);
                Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE,
                        Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
            }
        }
    }

    @OnClick({R.id.iv_back, R.id.ll_unload_chuanhuo_cb, R.id.lload_cuofen_cb, R.id.ll_touch_vibrate_cb, R.id.ll_auto_light})
    @Override
    protected void onClickBtn(View v) {
        super.onClickBtn(v);
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_unload_chuanhuo_cb:
                //卸车串货开关
                if (swUnloadChuanhuo.isChecked()) {
                    swUnloadChuanhuo.setChecked(false);
                } else {
                    swUnloadChuanhuo.setChecked(true);
                }
                sharedPreferUtil.setUnloadChuanhuoSwitch(swUnloadChuanhuo.isChecked());
                break;
            case R.id.lload_cuofen_cb:
                //装车错分强制开关
                LinearLayout layout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.alert_dialog_load_wrong_force_ok, null);
                final EditText password = layout.findViewById(R.id.load_wrong_force_password);
                Button sureButton = layout.findViewById(R.id.load_wrong_force_ok);
                Button cancleButton = layout.findViewById(R.id.load_wrong_force_cancle);
                final Dialog dialog = new Dialog(this, R.style.AsyncTaskDialog);
                dialog.addContentView(layout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                dialog.getWindow().getDecorView().setPadding(10, 0, 10, 0);
                dialog.setCanceledOnTouchOutside(false);
                dialog.setCancelable(false);
                dialog.show();

                sureButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String pwd = password.getText().toString();
                        if (!getString(R.string.load_wrong_force_pwd).equals(pwd)) {
                            //提示密码错误
                            showToast(getString(R.string.wrong_pwd));
                            return;
                        }
                        if (swLoadCuofen.isChecked()) {
                            swLoadCuofen.setChecked(false);
                        } else {
                            swLoadCuofen.setChecked(true);
                        }
                        sharedPreferUtil.setBooleanValue(Common.LOAD_WRONG_FORCE_SURE, swLoadCuofen.isChecked());
                        dialog.dismiss();
                    }
                });
                cancleButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        boolean isCheck = sharedPreferUtil.getBooleanValue(Common.LOAD_WRONG_FORCE_SURE);
                        if (isCheck) {
                            swLoadCuofen.setChecked(true);
                        } else {
                            swLoadCuofen.setChecked(false);
                        }
                        dialog.dismiss();
                    }
                });
                break;
            case R.id.ll_touch_vibrate_cb:
                //触屏震动开关
                if (swTouchVibrate.isChecked()) {
                    swTouchVibrate.setChecked(false);
                    sharedPreferUtil.setBooleanValue(Common.PLAY_VIBRATOR, false);
                } else {
                    swTouchVibrate.setChecked(true);
                    sharedPreferUtil.setBooleanValue(Common.PLAY_VIBRATOR, true);
                }
                break;
            case R.id.ll_auto_light:
                //亮度调节设置
                if (hasWriteSettingPermission()) {
                    ContentResolver contentResolver = getContentResolver();
                    if (swAutoLight.isChecked()) {
                        //手动调节亮度
                        swAutoLight.setChecked(false);
                        Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE,
                                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
                        ll_brightness.setVisibility(View.VISIBLE);
                        sharedPreferUtil.setBooleanValue(Common.AUTO_LIGHT, false);
                    } else {
                        //选中则自适应亮度
                        swAutoLight.setChecked(true);
                        Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE,
                                Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
                        ll_brightness.setVisibility(View.GONE);
                        sharedPreferUtil.setBooleanValue(Common.AUTO_LIGHT, true);
                    }
                }
                break;
            default:
                break;
        }
    }

    /**
     * 获得当前屏幕亮度值  0--255
     */
    private int getScreenBrightness() {
        int screenBrightness = 255;
        try {
            screenBrightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return screenBrightness;
    }

    /**
     * 设置当前系统的亮度值:0~255
     */
    public void setSysScreenBrightness(int brightness) {
        //设置透明值
        ivBigBrightness.setAlpha((float) brightness / 255);
        //设置透明值取反
        ivSmallBrightness.setAlpha((float) (255 - brightness) / 255);
        if (brightness == 0) {
            ivBigBrightness.setAlpha((float) 0.1);
        }
        if (255 - brightness == 0) {
            ivSmallBrightness.setAlpha((float) 0.1);
        }
        if (hasWriteSettingPermission()) {
            ContentResolver resolver = getContentResolver();
            Uri uri = Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS);
            Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
            // 实时通知改变
            resolver.notifyChange(uri, null);
        }
    }

    /**
     * 是否获取系统设置权限
     */
    private boolean hasWriteSettingPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.System.canWrite(SpecificActivity.this)) {
                if (mDialog == null) {
                    mDialog = new MyDialog(SpecificActivity.this);
                }
                mDialog.setIcon(R.drawable.alert);
                mDialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
                mDialog.setTitle("提示");
                mDialog.setMessage("需要修改系统设置权限才能生效，是否去需改？");
                mDialog.setPositiveClickListener( "是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
                        intent.setData(Uri.parse("package:" + getPackageName()));
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                });
                mDialog.setNegativeClickListener(R.drawable.btn_login_selector, "否", null);
                mDialog.setCanceledOnTouchOutside(false);
                mDialog.setCancelable(false);
                mDialog.show();
                return false;
            }
        }
        return true;
    }
}
